%%%-------------------------------------------------------------------
%%% @author mirahs(2892727493@qq.com)
%%% @doc
%%%     mnesia 处理器
%%% @end
%%%-------------------------------------------------------------------
-module(db_mnesia_handler).

-export([
    get_ver/0
    ,get_tables/0

    ,ver_upgrade_before/0
    ,ver_upgrade/1
    ,init_after/0
]).

-include("common.hrl").
-include("mnesia.hrl").
-include("env.hrl").
-include("role.hrl").
-include("role_data.hrl").

-define(ver, 1).
-define(file_merge_ok, "merge_ok.mb").


%%%===================================================================
%%% API functions
%%%===================================================================

get_ver() ->
    ?ver.

get_tables() ->
    [
        #mnesia_table{table = mnesia_info, record_name = mnesia_info, attributes = record_info(fields, mnesia_info), copies = disc_copies, index = []}

        ,#mnesia_table{table = role_base, record_name = role_base, attributes = record_info(fields, role_base), copies = ram_copies, index = [#role_base.account, #role_base.name]}
        ,#mnesia_table{table = role_data, record_name = role_data, attributes = record_info(fields, role_data), copies = disc_only_copies, index = []}
        ,#mnesia_table{table = role_offline_async, record_name = role_offline_async, attributes = record_info(fields, role_offline_async), copies = disc_only_copies, index = [#role_offline_async.rid], parse = role_offline_async_parse}
    ].


ver_upgrade_before() ->
    % 只应用新的字段列表, 不改变数据
    mnesia:transform_table(role_base, fun(R) -> R end, record_info(fields, role_base), role_base),
    ok.

ver_upgrade(?ver) ->
    ok.

init_after() ->
    DirVar = env_mgr:get(?ENV_DIR_VAR),
    FilePath = lists:concat([DirVar, ?file_merge_ok]),

    case filelib:is_file(FilePath) of
        false -> ok;
        true ->
            ?INFO("合服mnesia文件(~s)加载开始", [FilePath]),
            {ok, Tabs} = db_mnesia:restore(filename:basename(?file_merge_ok, ".mb")),
            ?INFO("合服mnesia文件(~s)加载成功(~w)", [FilePath, Tabs]),
            ok = file:delete(FilePath),
            ?INFO("合服mnesia文件(~s)删除成功", [FilePath])
    end.
